package Net.data;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import Util.CryptoUtil;
import baidupcs.api.BaiduPcs;
import baidupcs.auth.AccessToken;
import baidupcs.error.api.BaiduPcsException;
import baidupcs.request.api.Order;
import baidupcs.request.api.OrderBy;
import baidupcs.response.api.FileMetaWithExtra;


public class GetData {

    private final static Logger logger = LogManager.getLogger(GetData.class.getName());

    private BaiduPcs pcs;

    public void getData(String Mac) {

        List<FileMetaWithExtra> list;
        try {
            list = pcs.list("/" + Mac + "/Data/", OrderBy.TIME, Order.ASC, 0, 1);

            for (FileMetaWithExtra file : list) {

               /* BufferedInputStream r = new BufferedInputStream(pcs.
                        download("/" + Mac + "/Data/" + file.getFileName()).in());
                String str = null;
                StringBuilder sb = new StringBuilder();
                while ((str = r.readLine()) != null) {
                    sb.append(str + "\n");
                }*/
                //断点超过100w会超出byte数组界限
            	long len = pcs.download("/" + Mac + "/Data/" + file.getFileName()).in().available();
            	logger.info(len);
            	if(len >= 10000000){
            		 pcs.delete(Mac + "/Data/" + file.getFileName());
            		 logger.info("文件长度过长，直接删除," + len);
            		 return;
            	}
                byte b[] = IOUtils.toByteArray(pcs.
                        download("/" + Mac + "/Data/" + file.getFileName()).in());
                
                
                logger.info(file.getFileName() + "的文件长度为：" + b.length);
                File encryptFile = new File(Mac + "/Data/" + file.getFileName());
                FileOutputStream fout = new FileOutputStream(encryptFile);
                fout.write(b);
                fout.close();
                
                CryptoUtil.getDecode(encryptFile);
                
                pcs.delete(Mac + "/Data/" + file.getFileName());
            }
        } catch (BaiduPcsException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getErrorResponse());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public GetData(AccessToken ac) {
        // TODO Auto-generated constructor stub
        this.pcs = new BaiduPcs(ac);
    }

}